package com.aube.plugin.draw;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.episode.list.VideoListActivity;
import com.aube.plugin.figure.CharacterActivity;
import com.aube.plugin.origin.R;
import com.aube.plugin.wap.H5WrapperActivity;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.model.Character;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;
import com.ryg.dynamicload.internal.DLIntent;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/8/12.
 */
public class WidgetDraw extends DLLayout {

    private Context context;
    private IPositionManager mManager;

    private LinearLayout mLayoutGroup, mLayoutState;
    private AtomicBoolean mAnimated = new AtomicBoolean(false);
    private View mFlag, mHeadLayout;
    private TextView mMore, mTitle, mDrawDes;
    private ImageView mArrow;
    private DrawLayout mDrawState;

    private FixedSizeImageView mImg;

    private CategorySimple mCate;
    private boolean mNeedUpdate = false;

    public WidgetDraw(Context context) {
        this(context, null);
    }
    public WidgetDraw(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public WidgetDraw(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    @Override
    public void initViews() {
        inflate(R.layout.widget_draw, this, true);
        mLayoutGroup = (LinearLayout) findViewById(R.id.draw_widget_group);

        mFlag = findViewById(R.id.header_flag);
        mTitle = (TextView) findViewById(R.id.header_widget_title);
        mMore = (TextView) findViewById(R.id.header_widget_more);
        mHeadLayout = findViewById(R.id.header_widget_layout);

        mDrawDes = (TextView) findViewById(R.id.draw_des);
        mLayoutState = (LinearLayout) findViewById(R.id.draw_widget_state);

        mArrow = (ImageView) findViewById(R.id.header_widget_arrow);
        mArrow.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_rightarrow));

        mFlag.setAlpha(0f);
        mTitle.setAlpha(0f);
        mMore.setAlpha(0f);
        mArrow.setAlpha(0f);
    }

    @Override
    public void fillData(Object object) {
        if(object == null || !(object instanceof Category))
            return;
        Category category = (Category) object;
        mCate = category.getSimpleCategory();

        mTitle.setText(category.modelName);
        if(StringUtils.isNotBlank(category.modelDesc)) {
            mMore.setText(category.modelDesc);
            mHeadLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
        } else {
            mMore.setVisibility(View.GONE);
            mArrow.setVisibility(View.GONE);
        }

        List list = (List) category.dataDetail;
        final DrawModel item = getDrawModel(list);

        if(item != null) {
            if(StringUtils.isNotBlank(item.picUrl)) {
                mImg = new FixedSizeImageView(getContext());
                mImg.setScaleType(ImageView.ScaleType.CENTER_CROP);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                mLayoutGroup.addView(mImg, params);
                mImg.updateSize(item.width, item.height);
                ImageLoader.getInstance(getContext()).fillImage(mImg, item.picUrl);

                mImg.setAlpha(0f);
            }

            if(StringUtils.isNotBlank(item.detailUrl)) {
                mImg.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //do jump
                        parseSchema(item.detailUrl);
                    }
                });
            }

            mDrawDes.setText(item.drawDesc);
            DisplayMetrics dm = getResources().getDisplayMetrics();
            int marginDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, dm);
            mDrawDes.setPadding(0, 0, marginDP, 0);
            mDrawState = (DrawLayout) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), DrawLayout.class.getName());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mLayoutState.addView(mDrawState, params);

            if(StringUtils.isBlank(item.drawUrl)) {
                mDrawState.update(item.drawFlag, false);
            } else {
                mDrawState.update(item.drawFlag, true);
                mDrawState.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        if(mBridge != null)
//                            mBridge.onClickToWap("", item.drawUrl, true);
                        parseSchema(item.drawUrl);
                    }
                });
            }

            mDrawDes.setAlpha(0f);
            mDrawState.setAlpha(0f);
        }
    }

    @Override
    public void update(Object data) {
        if(data == null || !(data instanceof Category))
            return;
        Category category = (Category) data;
        mCate = category.getSimpleCategory();

        refreshData(category);
    }

    @Override
    public void update() {
        getData();
    }

    /**
     * 跳到抽奖关联的具体模块详情里面去
     * @param url
     */
    private void parseSchema(String url) {
        Utils.sysout("**********************url:" + url);
        if(mBridge == null)
            return;
        mNeedUpdate = true;
        Utils.sysout("**********************mBridge not null:" + url.indexOf("://"));
        try {
            if(url.startsWith("http") || url.indexOf("://") == -1) {
                DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.wap.H5WrapperActivity");
                intent.putExtra(H5WrapperActivity.WEB_POST, true);
                intent.putExtra(H5WrapperActivity.WEB_URL, url);
                mBridge.openPluginActivity(intent);
                return;
            }

            Uri uri = Uri.parse(url);
            String type = uri.getQueryParameter("type");
            Utils.sysout("**********************type:" + type);
            if(StringUtils.isBlank(type))
                return;
            if("login".equalsIgnoreCase(type)) {
                //to login
                mBridge.isUserLogin();
                Utils.sysout("**********************login");
            } else if("actor".equalsIgnoreCase(type)) {
                //to CharacterActivity
                String relatedId = uri.getQueryParameter("relatedId");
                Utils.sysout("**********************CharacterActivity");
                if(StringUtils.isNotBlank(relatedId)) {
                    DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.figure.CharacterActivity");
                    Character character = new Character();
                    character.relatedId = relatedId;
                    intent.putExtra(CharacterActivity.ACTOR, character);
                    mBridge.openPluginActivity(intent);
                }
            } else if("playVideo".equalsIgnoreCase(type)) {
                Utils.sysout("**********************videoid");
                //to play video
                String videoid = uri.getQueryParameter("videoid");
                if(StringUtils.isBlank(videoid))
                    return;
                String videono = uri.getQueryParameter("videono");
                ChannelDetail channelDetail = new ChannelDetail();
                channelDetail.videoid = videoid;
                channelDetail.videono = videono;
                mBridge.onClickToVideo(channelDetail, null);
            } else if("moreList".equalsIgnoreCase(type)) {
                //to list
                Utils.sysout("**********************list");
                String templateCode = uri.getQueryParameter("templateCode");
                String relatedId = uri.getQueryParameter("relatedId");
                String modelCode = uri.getQueryParameter("modelCode");
                String subModelCode = uri.getQueryParameter("subModelCode");

                if(StringUtils.isBlank(modelCode))
                    return;

                Category category = new Category();
                category.templateType = templateCode;
                category.relatedId = relatedId;
                category.modelCode = modelCode;
                category.subModelCode = subModelCode;
                if("episode".equalsIgnoreCase(modelCode)) {
                    Utils.sysout("**********************episode");
                    DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.episode.list.VideoListActivity");
                    intent.putExtra(VideoListActivity.CATEGORY, category);
                    mBridge.openPluginActivity(intent);
                } else if("stagephoto".equalsIgnoreCase(modelCode)) {
                    Utils.sysout("**********************photo");
                    DLIntent intent = new DLIntent("com.aube.plugin.gallery", "com.aube.plugin.gallery.GalleryListActivity");
                    intent.putExtra("GALLERY", category.getSimpleCategory());
                    mBridge.openPluginActivity(intent);
                } else if("actor_week_rank".equalsIgnoreCase(modelCode)) {
                    Utils.sysout("**********************weekrank");
                    String selectedWeek = uri.getQueryParameter("selectedWeek");
                    DLIntent intent = new DLIntent("com.aube.plugin.rank", "com.aube.plugin.rank.WeekRankActivity");
                    intent.putExtra("INTENT_CATEGORY", category.getSimpleCategory());
                    mBridge.openPluginActivity(intent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        if(mNeedUpdate)
            getData();
    }

    /**
     * 模块内容接口
     * templateCode(index | actor)
     * ostype(iphone|android)
     * modelCode（template接口中获取）
     * relatedId（有就传，比如嘉宾）
     * lastId（分页用，第一次可不传，当前页最后一个id）
     * maxnum（一页最大条数）
     */
    public void getData() {
        HashMap<String, String> params = new HashMap<>();
        params.put(Constant.API_REQUEST_METHOD, "com.aube.app.model.data.detail");
        params.put("templateCode", mCate.templateType);
        params.put("modelCode", mCate.modelCode);
        params.put("relatedId", mCate.relatedId);
        params.put("maxnum", "100");
        params.put("subModelCode", mCate.subModelCode);

        if(mBridge != null) {
            mBridge.exeHttpRequest(params, CategoryListModel.class, null, new Response.Listener<CategoryListModel>() {
                @Override
                public void onResponse(CategoryListModel response) {
                    if (response == null || !response.success())
                        return;
                    if(response.data != null && response.data.size() > 0)
                        refreshData(response.data.get(0));
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                }

                @Override
                public void onStart() {
                }
            });
        }
    }

    private void refreshData(Category category) {
        if(category == null) {
            return;
        }
        if (mCate.modelCode.equalsIgnoreCase(category.modelCode)) {
            List list = (List) category.dataDetail;
            final DrawModel item = getDrawModel(list);

            if(item != null) {
                mDrawDes.setText(item.drawDesc);

                if(mDrawState != null) {
                    if (StringUtils.isBlank(item.drawUrl)) {
                        mDrawState.update(item.drawFlag, false);
                        mDrawState.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //do nothing
                            }
                        });
                    } else {
                        mDrawState.update(item.drawFlag, true);
                        mDrawState.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
//                                    if (mBridge != null)
//                                        mBridge.onClickToWap("", item.drawUrl, true);
                                parseSchema(item.drawUrl);
                            }
                        });
                    }
                }
            }
        }
    }

    private DrawModel getDrawModel(List list) {
        for(Object obj : list) {
            DrawModel item = new DrawModel();

            LinkedHashMap<String, Object> lhm = (LinkedHashMap<String, Object>) obj;
            Iterator<String> keyIterator = lhm.keySet().iterator();
            while (keyIterator.hasNext()) {
                String key = keyIterator.next();
                Object value = lhm.get(key);

                item.setItem(key, value);
            }
            return item;
        }
        return null;
    }

    private void showHeader(int animDelay) {
        ObjectAnimator alphaTitle = ObjectAnimator.ofFloat(mTitle, "alpha", 0, 1);
        alphaTitle.setDuration(300);
        if(animDelay > 0)
            alphaTitle.setStartDelay(animDelay);

        ObjectAnimator alphaDes = ObjectAnimator.ofFloat(mMore, "alpha", 0, 1);
        alphaDes.setDuration(300);
        alphaDes.setStartDelay(400 + animDelay);

        ObjectAnimator alphaArrow = ObjectAnimator.ofFloat(mArrow, "alpha", 0, 1);
        alphaArrow.setDuration(300);
        alphaArrow.setStartDelay(400 + animDelay);

        ObjectAnimator translate = ObjectAnimator.ofFloat(mFlag, "translationY", -mFlag.getHeight(), 0);
        translate.setDuration(300);
        translate.setStartDelay(800 + animDelay);
        translate.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mFlag.setAlpha(1f);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(alphaTitle, alphaDes, alphaArrow, translate);
        mSet.start();
    }

    private void animImgAndtip(int delay) {
        if(mImg != null) {
            ValueAnimator imgAnim = ValueAnimator.ofFloat(0, 1);
            imgAnim.setDuration(300);
            imgAnim.setStartDelay(delay);
            imgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    mImg.setAlpha(value);
                }
            });
            imgAnim.start();
        }

        ValueAnimator desAnim = ValueAnimator.ofFloat(0, 1);
        desAnim.setDuration(300);
        desAnim.setStartDelay(200 + delay);
        desAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mDrawDes.setAlpha(value);
            }
        });
        desAnim.start();

        if(mDrawState != null) {
            ValueAnimator stateAnim = ValueAnimator.ofFloat(0, 1);
            stateAnim.setDuration(300);
            stateAnim.setStartDelay(400 + delay);
            stateAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    mDrawState.setAlpha(value);
                }
            });
            stateAnim.start();
        }
    }

    @Override
    public void notifyAnim(final int animDelay) {
        if(mManager == null)
            return;
        if(mAnimated.get())
            return;
        mAnimated.set(true);
        mLayoutGroup.setVisibility(View.VISIBLE);
        showHeader(animDelay);
        animImgAndtip(animDelay + 400);
//        if(mAnimItems == null)
//            return;
//        notifyItemAnim(animDelay + 300);
    }

//    private void notifyItemAnim(int animDelay) {
//        int i=0;
//        for(IPositionListener item : mAnimItems) {
//            item.notifyAnim(animDelay + i*200);
//            i++;
//        }
//    }

    @Override
    public void registToManager(IPositionManager manager) {
        if(mManager != null || manager == null)
            return;
        manager.add(this);
        this.mManager = manager;

        mLayoutGroup.setVisibility(View.INVISIBLE);
    }

    @Override
    public void unreistFromManager(IPositionManager manager) {
        if(mManager == null || manager == null)
            return;
        manager.remove(this);
        this.mManager = null;
    }

    @Override
    public int[] getLocations() {
        int[] locs = new int[2];
        getLocationOnScreen(locs);
        return locs;
    }

    @Override
    public void setTheme(int themeColor) {
        mFlag.setBackgroundColor(themeColor);
    }
}
